<template>
  <div class="contract-create">
    <el-card>
      <template #header>
        <div class="card-header">
          <h3>生成合同</h3>
        </div>
      </template>

      <!-- 合同表单 -->
      <el-form
        ref="contractFormRef"
        :model="contractForm"
        :rules="rules"
        label-width="120px"
        class="contract-form"
      >
        <!-- 基本信息 -->
        <el-divider>基本信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="贷款编号" prop="loanNo">
              <el-select
                v-model="contractForm.loanNo"
                placeholder="请选择贷款"
                filterable
                remote
                :remote-method="searchLoans"
                :loading="loading"
                value-key="no"
                @change="handleLoanChange"
                style="width: 100%"
                clearable
              >
                <el-option
                  v-for="item in loanOptions"
                  :key="item.id"
                  :label="item.no"
                  :value="item.no"
                >
                  <span>{{ item.no }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">
                    {{ item.customerName }}
                  </span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合同模板" prop="templateId">
              <el-select v-model="contractForm.templateId" placeholder="请选择合同模板" style="width: 100%">
                <el-option label="个人贷款合同" value="personal" />
                <el-option label="企业贷款合同" value="enterprise" />
                <el-option label="抵押贷款合同" value="mortgage" />
                <el-option label="担保贷款合同" value="guarantee" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="签订日期" prop="signDate">
              <el-date-picker
                v-model="contractForm.signDate"
                type="date"
                placeholder="选择日期"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="生效日期" prop="effectiveDate">
              <el-date-picker
                v-model="contractForm.effectiveDate"
                type="date"
                placeholder="选择日期"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="到期日期" prop="expiryDate">
              <el-date-picker
                v-model="contractForm.expiryDate"
                type="date"
                placeholder="选择日期"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 借款人和贷款人信息 -->
        <el-divider>合同当事人</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="借款人姓名" prop="borrower">
              <el-input v-model="contractForm.borrower" placeholder="请输入借款人姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="借款人证件号" prop="borrowerIdCard">
              <el-input v-model="contractForm.borrowerIdCard" placeholder="请输入借款人证件号" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="贷款人名称" prop="lender">
              <el-input v-model="contractForm.lender" placeholder="请输入贷款人名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="贷款人代表" prop="lenderRepresentative">
              <el-input v-model="contractForm.lenderRepresentative" placeholder="请输入贷款人代表" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 担保信息 -->
        <el-divider>担保信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="担保方式" prop="guaranteeType">
              <el-select v-model="contractForm.guaranteeType" placeholder="请选择担保方式" style="width: 100%">
                <el-option label="信用" value="credit" />
                <el-option label="保证" value="guarantee" />
                <el-option label="抵押" value="mortgage" />
                <el-option label="质押" value="pledge" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="利率(%)" prop="interestRate">
              <el-input-number v-model="contractForm.interestRate" :min="0" :precision="2" :step="0.1" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20" v-if="contractForm.guaranteeType === 'guarantee'">
          <el-col :span="24">
            <el-form-item label="担保人" prop="guarantor">
              <el-input v-model="contractForm.guarantor" placeholder="请输入担保人姓名" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20" v-if="contractForm.guaranteeType === 'mortgage' || contractForm.guaranteeType === 'pledge'">
          <el-col :span="24">
            <el-form-item label="担保物描述" prop="collateralDesc">
              <el-input
                v-model="contractForm.collateralDesc"
                type="textarea"
                rows="3"
                placeholder="请输入担保物详细描述"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 特殊条款 -->
        <el-divider>特殊条款</el-divider>
        <el-form-item label="特殊约定" prop="specialTerms">
          <el-input
            v-model="contractForm.specialTerms"
            type="textarea"
            rows="3"
            placeholder="请输入特殊约定条款"
          />
        </el-form-item>

        <!-- 操作按钮 -->
        <el-form-item>
          <el-button type="primary" @click="generateContract(contractFormRef)">生成合同</el-button>
          <el-button type="success" @click="previewContract" :disabled="!contractGenerated">预览合同</el-button>
          <el-button type="warning" @click="downloadContract" :disabled="!contractGenerated">下载合同</el-button>
          <el-button type="info" @click="generateRepaymentPlan" :disabled="!contractGenerated">生成还款计划</el-button>
          <el-button @click="resetForm(contractFormRef)">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 预览弹窗 -->
    <el-dialog
      v-model="previewVisible"
      title="合同预览"
      width="80%"
      :before-close="handleClose"
    >
      <div class="preview-toolbar">
        <el-button type="primary" @click="downloadContract">下载</el-button>
        <el-button type="success" @click="window.print()">打印</el-button>
      </div>
      <div class="preview-content">
        <p>合同预览内容</p>
        <p>实际开发中这里应该是使用iframe嵌入PDF预览或者使用专门的PDF预览组件</p>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { contractApi } from '@/api/contract'
import { useRouter } from 'vue-router'

const router = useRouter()

// 表单引用
const contractFormRef = ref(null)

// 表单数据
const contractForm = reactive({
  loanNo: '',
  templateId: '',
  contractNo: 'HT' + new Date().getTime(),
  signDate: '',
  effectiveDate: '',
  expiryDate: '',
  borrower: '',
  borrowerIdCard: '',
  lender: '示例金融公司',
  lenderRepresentative: '',
  guaranteeType: '',
  guarantor: '',
  collateralDesc: '',
  interestRate: 4.35,
  specialTerms: ''
})

// 表单验证规则
const rules = {
  loanNo: [
    { required: true, message: '请选择贷款', trigger: 'change' }
  ],
  templateId: [
    { required: true, message: '请选择合同模板', trigger: 'change' }
  ],
  signDate: [
    { required: true, message: '请选择签订日期', trigger: 'change' }
  ],
  effectiveDate: [
    { required: true, message: '请选择生效日期', trigger: 'change' }
  ],
  expiryDate: [
    { required: true, message: '请选择到期日期', trigger: 'change' }
  ],
  borrower: [
    { required: true, message: '请输入借款人姓名', trigger: 'blur' }
  ],
  borrowerIdCard: [
    { required: true, message: '请输入借款人证件号', trigger: 'blur' },
    { pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '请输入正确的身份证号', trigger: 'blur' }
  ],
  lender: [
    { required: true, message: '请输入贷款人名称', trigger: 'blur' }
  ],
  guaranteeType: [
    { required: true, message: '请选择担保方式', trigger: 'change' }
  ]
}

// 贷款选项
const loanOptions = ref([])
const loading = ref(false)
const selectedLoan = ref(null) // 保存用户选择的贷款

// 搜索贷款
const searchLoans = async (query) => {
  if (query) {
    loading.value = true
    try {
      // 真实API调用
      // 使用setTimeout模拟API延迟，实际开发中应该调用真实API
      setTimeout(() => {
        // 保存这些数据到本地，避免API调用失败导致数据丢失
        const loansData = [
          { id: 1, no: 'DK202401001', customerName: '张三' },
          { id: 2, no: 'DK202401002', customerName: '李四' },
          { id: 3, no: 'DK202401003', customerName: '王五' }
        ]
        
        loanOptions.value = loansData.filter(
          item => item.no.includes(query) || item.customerName.includes(query)
        )
        
        // 如果用户之前已选择了贷款，确保选项中包含它
        if (contractForm.loanNo && !loanOptions.value.some(item => item.no === contractForm.loanNo)) {
          const existingLoan = loansData.find(item => item.no === contractForm.loanNo)
          if (existingLoan) {
            loanOptions.value.unshift(existingLoan)
          }
        }
        
        loading.value = false
      }, 500)
    } catch (error) {
      console.error('搜索贷款失败:', error)
      loading.value = false
    }
  } else {
    // 当查询为空时，显示所有选项或最近的选项
    setTimeout(() => {
      loanOptions.value = [
        { id: 1, no: 'DK202401001', customerName: '张三' },
        { id: 2, no: 'DK202401002', customerName: '李四' },
        { id: 3, no: 'DK202401003', customerName: '王五' }
      ]
      
      // 确保已选择的贷款显示在选项中
      if (contractForm.loanNo && !loanOptions.value.some(item => item.no === contractForm.loanNo)) {
        const existingLoan = { id: 0, no: contractForm.loanNo, customerName: '(已选择)' }
        loanOptions.value.unshift(existingLoan)
      }
      
      loading.value = false
    }, 300)
  }
}

// 处理贷款选择变更
const handleLoanChange = (value) => {
  console.log('贷款选择变更:', value)
  // 保存选择的贷款信息
  selectedLoan.value = loanOptions.value.find(item => item.no === value)
  
  // 可以在这里自动填充一些字段，例如借款人信息
  if (selectedLoan.value) {
    contractForm.borrower = selectedLoan.value.customerName
  }
}

// 合同生成状态
const contractGenerated = ref(false)
const previewVisible = ref(false)
const previewUrl = ref('')
const contractId = ref(null)

// 生成合同
const generateContract = async (formEl) => {
  if (!formEl) return

  try {
    await formEl.validate()
    
    loading.value = true
    console.log('正在生成合同，贷款编号:', contractForm.loanNo)
    
    // 转换表单数据为API需要的格式
    const data = {
      loanNo: contractForm.loanNo,
      templateId: contractForm.templateId,
      signDate: contractForm.signDate,
      effectiveDate: contractForm.effectiveDate,
      expiryDate: contractForm.expiryDate,
      borrower: contractForm.borrower,
      borrowerIdCard: contractForm.borrowerIdCard,
      lender: contractForm.lender,
      lenderRepresentative: contractForm.lenderRepresentative,
      guaranteeType: contractForm.guaranteeType,
      guarantor: contractForm.guarantor,
      collateralDesc: contractForm.collateralDesc,
      interestRate: contractForm.interestRate,
      remark: contractForm.specialTerms
    }
    
    try {
      const res = await contractApi.generate(data)
      console.log('合同生成成功，结果:', res)
      contractGenerated.value = true
      contractId.value = res.data.contractId
      previewUrl.value = res.data.previewUrl
      
      // 确保贷款编号依然存在
      if (selectedLoan.value) {
        // 如果当前选项列表中不包含已选中的贷款，则添加
        if (!loanOptions.value.some(item => item.no === contractForm.loanNo)) {
          loanOptions.value.unshift(selectedLoan.value)
        }
      }
      
      ElMessage.success('合同生成成功')
    } catch (error) {
      console.error('合同生成失败:', error)
      ElMessage.error('合同生成失败')
    } finally {
      loading.value = false
    }
  } catch (error) {
    console.error('表单验证失败:', error)
    ElMessage.error('请填写完整的合同信息')
  }
}

// 获取贷款详情
const fetchLoanDetails = async (loanNo) => {
  if (!loanNo) return
  
  try {
    loading.value = true
    console.log('获取贷款详情:', loanNo)
    
    // 模拟获取贷款详情的API调用
    setTimeout(() => {
      // 获取到贷款详情后，填充表单
      const loanDetail = {
        borrower: '张三',
        borrowerIdCard: '110101199001011234',
        interestRate: 4.35,
        guaranteeType: 'credit',
        loanAmount: 100000
      }
      
      // 填充表单数据
      contractForm.borrower = loanDetail.borrower
      contractForm.borrowerIdCard = loanDetail.borrowerIdCard
      contractForm.interestRate = loanDetail.interestRate
      contractForm.guaranteeType = loanDetail.guaranteeType
      
      loading.value = false
    }, 500)
  } catch (error) {
    console.error('获取贷款详情失败:', error)
    loading.value = false
  }
}

// 监听贷款编号变化
const watchLoanNo = (newVal) => {
  if (newVal) {
    fetchLoanDetails(newVal)
  }
}

// 预览合同
const previewContract = () => {
  if (contractId.value) {
    loading.value = true
    
    contractApi.preview(contractId.value).then(res => {
      // 创建Blob对象并打开预览窗口
      const blob = new Blob([res.data], { type: 'application/pdf' })
      const url = window.URL.createObjectURL(blob)
      window.open(url, '_blank')
      window.URL.revokeObjectURL(url)
      
      loading.value = false
    }).catch(() => {
      loading.value = false
    })
  } else {
    previewVisible.value = true
  }
}

// 关闭预览
const handleClose = () => {
  previewVisible.value = false
}

// 打印合同
const printContract = () => {
  // 调用打印功能
  window.print()
}

// 下载合同
const downloadContract = () => {
  if (contractId.value) {
    loading.value = true
    
    contractApi.download(contractId.value).then(res => {
      // 处理文件下载
      const blob = new Blob([res.data])
      const url = window.URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = url
      link.download = `合同-${contractForm.loanNo}.pdf`
      link.click()
      window.URL.revokeObjectURL(url)
      
      ElMessage.success('合同下载成功')
      loading.value = false
    }).catch(() => {
      loading.value = false
    })
  } else {
    ElMessage.warning('请先生成合同')
  }
}

// 重置表单
const resetForm = (formEl) => {
  if (!formEl) return
  formEl.resetFields()
  contractGenerated.value = false
  contractId.value = null
}

// 生成还款计划
const generateRepaymentPlan = () => {
  if (contractId.value) {
    loading.value = true
    
    const data = {
      contractId: contractId.value
    }
    
    contractApi.generatePlan(data).then(res => {
      ElMessage.success(`成功生成${res.data.planCount}期还款计划`)
      loading.value = false
    }).catch(() => {
      loading.value = false
    })
  } else {
    ElMessage.warning('请先生成合同')
  }
}

// 监听贷款编号变化
watch(() => contractForm.loanNo, (newVal) => {
  console.log('贷款编号变化:', newVal)
  if (newVal) {
    watchLoanNo(newVal)
  }
})

// 初始化
onMounted(() => {
  // 如果URL中包含贷款编号参数，自动填充
  const urlParams = new URLSearchParams(window.location.search)
  const loanNoFromUrl = urlParams.get('loanNo')
  
  if (loanNoFromUrl) {
    contractForm.loanNo = loanNoFromUrl
    // 触发贷款详情获取
    setTimeout(() => {
      fetchLoanDetails(loanNoFromUrl)
    }, 300)
  }
})
</script>

<style scoped>
.contract-create {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.contract-form {
  margin-top: 20px;
}

.el-divider {
  margin: 24px 0;
}

.preview-toolbar {
  margin-bottom: 20px;
  text-align: right;
}

.preview-content {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 20px;
  background-color: #fff;
}
</style> 